﻿using SimpleJSON;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UpdateChecker : MonoBehaviour
{
    public string UpdatePath;
    public string Channel;
    public string System;
    public string Platform;
    public int Major;
    public int Minor;
    public int Patch;
    // Use this for initialization
    void Start()
    {
        if (string.IsNullOrEmpty(UpdatePath))
        {
            return;
        }
        StartCoroutine(checkUpdate());
    }

    private IEnumerator checkUpdate()
    {
        string jsonPath = UpdatePath + Channel + "-" + System + "-" + Platform + ".json";
        Debug.Log(jsonPath);
        WWW www = new WWW(jsonPath);
        yield return www;
        if (www.isDone)
        {
            string text = www.text;
            Debug.Log(text);
            JSONNode json = JSONNode.Parse(text);
            JSONNode verison = json["version"];
            int upMajor = verison["major"].AsInt;
            int upMinor = verison["minor"].AsInt;
            int upPatch = verison["patch"].AsInt;
            string packagePath = json["lastVersionPath"];
            string versionInfo = "当前版本：" + Major + "." + Minor + "." + Patch
                + " 最新版本:" + upMajor + "." + upMinor + "." + upPatch;
            if (upMajor > Major)
            {
                ShowDialog("有重大版本更新，如果不更新可能无法正常使用。\n" + versionInfo,
                    () => { this.Download(packagePath); });
            }
            else if (upMajor < Major)
            {
                yield break;
            }
            else if (upMinor > Minor)
            {
                ShowDialog("有新功能更新，建议更新到最新版。\n" + versionInfo,
                    () => { this.Download(packagePath); });
            }
            else if (upMinor < Minor)
            {
                yield break;
            }
            else if (upPatch > Patch)
            {
                ShowDialog("有bug修复更新，建议更新到最新版。\n" + versionInfo,
                    () => { this.Download(packagePath); });
            }
        }
    }
    private void Download(string path)
    {
        Debug.Log("download new version:" + path);
        if (!path.StartsWith("http://"))
        {
            path = UpdatePath + path;
        }
        Application.OpenURL(path);
    }
    private void ShowDialog(string content, Action okCallbck)
    {
        GenericDialog dialog = GenericDialog.Instance();
        dialog.Title("更新");
        dialog.Message(content);
        dialog.OnAccept("Yes", () =>
        { // define what happens when user clicks Yes:
            dialog.Hide();
            okCallbck();
        });

        dialog.OnDecline("No thanks", () => dialog.Hide());
        dialog.Show();
    }
    // Update is called once per frame
    void Update()
    {

    }
}
